#include "hetao_socgi.h"

#include "LOGC.h"

/* test
curl -H "TOKEN_KEY: TOKEN_VALUE" "http://localhost/hello.socgi"
curl -H "TOKEN_KEY: TOKEN_VALU2" "http://localhost/hello.socgi"
*/

INITHTTPAPPLICATION InitHttpApplication ;
int InitHttpApplication( struct HttpApplicationContext *ctx )
{
	InfoLog( __FILE__ , __LINE__ , "InitHttpApplication" );
	
	return HTTP_OK;
}

PROCESSHTTPRESOURCE ProcessHttpResource ;
int ProcessHttpResource( struct HttpApplicationContext *ctx )
{
	char		*token ;
	int		token_len ;
	char		http_body[ 1024 ] ;
	int		http_body_len ;
	
	int		nret = 0 ;
	
	InfoLog( __FILE__ , __LINE__ , "ProcessHttpResource" );
	
	token = SOCGIQueryHttpHeaderPtr( ctx , "TOKEN_KEY" , & token_len ) ;
	if( token == NULL )
	{
		memset( http_body , 0x00 , sizeof(http_body) );
		http_body_len = SNPRINTF( http_body , sizeof(http_body)-1 , "token is null\n" ) ;
		nret = SOCGIFormatHttpResponse( ctx , http_body , http_body_len , NULL ) ;
		if( nret )
		{
			FatalLog( __FILE__ , __LINE__ , "SOCGIFormatHttpResponse failed[%d]" , nret );
			return HTTP_INTERNAL_SERVER_FATAL;
		}
		else
		{
			InfoLog( __FILE__ , __LINE__ , "SOCGIFormatHttpResponse ok" );
		}
		
		InfoLog( __FILE__ , __LINE__ , "none token for checking" );
		return HTTP_OK;
	}
	else if( STRNEQRSTR( token , token_len , "TOKEN_VALUE" ) )
	{
		InfoLog( __FILE__ , __LINE__ , "check token ok" );
		return 0;
	}
	else
	{
		memset( http_body , 0x00 , sizeof(http_body) );
		http_body_len = SNPRINTF( http_body , sizeof(http_body)-1 , "token[%.*s] is wrong\n" , token_len,token ) ;
		nret = SOCGIFormatHttpResponse( ctx , http_body , http_body_len , NULL ) ;
		if( nret )
		{
			FatalLog( __FILE__ , __LINE__ , "SOCGIFormatHttpResponse failed[%d]" , nret );
			return HTTP_INTERNAL_SERVER_FATAL;
		}
		else
		{
			InfoLog( __FILE__ , __LINE__ , "SOCGIFormatHttpResponse ok" );
		}
		
		InfoLog( __FILE__ , __LINE__ , "check token not matched" );
		return HTTP_OK;
	}
}

CALLHTTPAPPLICATION CallHttpApplication ;
int CallHttpApplication( struct HttpApplicationContext *ctx )
{
	char	http_body[ 1024 ] ;
	int	http_body_len ;
	
	int	nret = 0 ;
	
	InfoLog( __FILE__ , __LINE__ , "InitHttpApplication" );
	
	memset( http_body , 0x00 , sizeof(http_body) );
	http_body_len = SNPRINTF( http_body , sizeof(http_body)-1 , "hello test_socgi_demo_check_token.socgi\n" ) ;
	nret = SOCGIFormatHttpResponse( ctx , http_body , http_body_len , NULL ) ;
	if( nret )
	{
		ErrorLog( __FILE__ , __LINE__ , "SOCGIFormatHttpResponse failed[%d]" , nret );
		return HTTP_INTERNAL_SERVER_ERROR;
	}
	else
	{
		InfoLog( __FILE__ , __LINE__ , "SOCGIFormatHttpResponse ok" );
		return HTTP_OK;
	}
}

CLEANHTTPAPPLICATION CleanHttpApplication ;
int CleanHttpApplication( struct HttpApplicationContext *ctx )
{
	InfoLog( __FILE__ , __LINE__ , "CleanHttpApplication" );
	
	return HTTP_OK;
}

